package org.lys.jdbc.datasource;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
/**
 * @Description: 数据库连接池
 * 基本原理：
 * 	一开始就初始化n个连接存放在容器中，
 *  要用时从容器中取出，
 *  使用完连接后，将用过的连接归还给容器
 * @Copyright: 福州骏华信息有限公司 (c)2013
 * @Created Date : 2013-4-4
 * @Author lys
 */
public class MyDataSource {
	private static String url = "jdbc:mysql://localhost:3306/javatest";
	private static String user = "root";
	private static String password = "root";

	private static int initCount = 5;
	private static int maxCount = 10;
	private int currentCount = 0;

	LinkedList<Connection> connectionsPool = new LinkedList<Connection>();

	public MyDataSource() {
		try {
			for (int i = 0; i < initCount; i++) {
				this.connectionsPool.addLast(this.createConnection());
				this.currentCount++;
			}
		} catch (SQLException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public Connection getConnection() throws SQLException {
		synchronized (connectionsPool) {//多线程保护
			if (this.connectionsPool.size() > 0)
				return this.connectionsPool.removeFirst();

			if (this.currentCount < maxCount) {
				this.currentCount++;
				return this.createConnection();
			}

			throw new SQLException("已没有链接");
		}
	}

	public void free(Connection conn) {
		this.connectionsPool.addLast(conn);
	}

	private Connection createConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}
}
